from flask import make_response, request
from flask_jwt_extended import create_access_token,  jwt_required, get_jwt_identity, unset_jwt_cookies
from datetime import datetime
from common.resp import ajax_data, ajax_error, ajax_success
from core import app, db, jwt
from modules.user import UserModel


@app.route("/login", methods=['POST'])
def login():
    data = request.get_json()
    account = data['account']
    password = UserModel.md5_encrypt(data['password'])
    user = UserModel.query.filter_by(account=account, password=password).first()
    if not user:
        return ajax_error('用户不存在或密码错误')

    # 登录成功，更新登录时间
    user.login_time = datetime.now()
    db.session.commit()
    access_token = create_access_token(identity=data['account'])
    res = {'token':access_token, 'account': data['account'], 'nickname': user.nickname}
    return ajax_data(res, "登录成功")

@app.route("/getInfo", methods=['GET'])
@jwt_required()
def getInfo():
    account = get_jwt_identity();
    print(account)
    user = UserModel.query.filter_by(account=account).first()
    if not user:
        return ajax_error('用户不存在或密码错误')

    user_info = user.to_json()
    user_info.pop('password', 'id')
    res = {
        'code': 0,
        'user': user_info,
        'permissions':[  "*:*:*"],
        'roles': ['admin']
    }
    return res


@app.route("/getRouters", methods=['GET'])
@jwt_required()
def getRouters():
    routers = [
        {
            "name": "模型训练",
            "path": "/Train",
            "hidden": False,
            "component": "Layout",
            "alwaysShow": True,
            "meta": {
                "title": "模型训练",
                "icon": "chart",
                "noCache": False,
                "link": None
            },
             "children": [
                {
                    "name": "Models",
                    "path": "Models",
                    "hidden": False,
                    "component": "models/index",
                    "meta": {
                        "title": "模型管理",
                        "icon": "chart",
                        "noCache": False,
                        "link": None
                    }
                },{
                    "name": "Datasets",
                    "path": "Datasets",
                    "hidden": False,
                    "component": "dataset/index",
                    "meta": {
                        "title": "数据集管理",
                        "icon": "chart",
                        "noCache": False,
                        "link": None
                    }
                },{
                    "name": "Training",
                    "path": "Training",
                    "hidden": False,
                    "component": "training/index",
                    "meta": {
                        "title": "训练管理",
                        "icon": "chart",
                        "noCache": False,
                        "link": None
                    }
                }
            ]
        },{
            "name": "Collect",
            "path": "/Collect",
            "hidden": False,
            "component": "Layout",
            "meta": {
                "title": "图片采集",
                "icon": "chart",
                "noCache": False,
                "link": None
            },
             "children": [
                {
                    "name": "Camera",
                    "path": "Camera",
                    "hidden": False,
                    "component": "camera/index",
                    "meta": {
                        "title": "摄像机管理",
                        "icon": "chart",
                        "noCache": False,
                        "link": None
                    }
                },{
                    "name": "Collection",
                    "path": "Collection",
                    "hidden": False,
                    "component": "collection/index",
                    "meta": {
                        "title": "采集任务",
                        "icon": "chart",
                        "noCache": False,
                        "link": None
                    }
                }
            ]
        },{
            "name": "Images",
            "path": "/Images",
            "hidden": False,
            "component": "Layout",
            "meta": {
                "title": "图片标注",
                "icon": "chart",
                "noCache": False,
                "link": None
            },
             "children": [
                {
                    "name": "Image",
                    "path": "Image",
                    "hidden": False,
                    "component": "image/index",
                    "meta": {
                        "title": "图片管理",
                        "icon": "chart",
                        "noCache": False,
                        "link": None
                    }
                },
                {
                    "name": "ImageMark",
                    "path": "ImageMark",
                    "hidden": False,
                    "component": "image/mark",
                    "meta": {
                        "title": "图片标注",
                        "icon": "chart",
                        "noCache": False,
                        "link": None
                    }
                },
                {
                    "name": "ImageCheck",
                    "path": "ImageCheck",
                    "hidden": False,
                    "component": "image/check",
                    "meta": {
                        "title": "标注审核",
                        "icon": "chart",
                        "noCache": False,
                        "link": None
                    }
                }
            ]
        }
    ]
    return ajax_data(routers)


@app.route("/logout", methods=['GET'])
def logout():
    res = make_response(ajax_success("您已退出登录"))
    unset_jwt_cookies(res)
    # user = get_jwt_identity();
    return res

# 自定义过期令牌响应
@jwt.expired_token_loader
def expired_token_callback(jwt_header, jwt_payload):
    return ajax_error('登录已过期', 401)